package be.vdab.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.vdab.dao.VoorstellingDAO;
import be.vdab.entities.Reservatie;

/**
 * Servlet implementation class ReservatieMandjeServlet
 */
@WebServlet("/reservatiemandje.htm")
public class ReservatieMandjeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String VIEW = "WEB-INF/JSP/reservatieMandje.jsp";
	private static final String REDIRECT_VIEW = "/reservatiemandje.htm";
	private VoorstellingDAO voorstellingDAO = VoorstellingDAO.getInstance();

	@SuppressWarnings({ "unchecked"})
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = null;
		session = request.getSession();
		if (session != null) {
			Map<Long, Long> mandje = null;
			mandje = (Map<Long, Long>) session.getAttribute("mandje");
			if (mandje != null) {
				List <Reservatie> reservaties = new ArrayList<Reservatie>();
				Set<Long> reservatieNummers = mandje.keySet();
				Long totaal = 0L;
				for (Long nr : reservatieNummers) {
					reservaties.add(new Reservatie(voorstellingDAO.zoekVoorstelling(nr),
							mandje.get(nr)));
					totaal = totaal
							+ voorstellingDAO.zoekVoorstelling(nr).getPrijs()
							* mandje.get(nr);
				}
				request.setAttribute("reservaties", reservaties);
				request.setAttribute("totaal", totaal);
				request.getRequestDispatcher(VIEW).forward(request, response);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = null;
		session = request.getSession();
		if (session != null) {
			Map<Long, Long> mandje = null;
			mandje = (Map<Long, Long>) session.getAttribute("mandje");
			if (request.getParameter("nummers") != null) {
				try {
					for (String nummerAlsString : request
							.getParameterValues("nummers")) {
						long nummer = Long.parseLong(nummerAlsString);
						mandje.remove(nummer);
					}
					session.setAttribute("mandje", mandje);
					response.sendRedirect(request.getContextPath()
							+ REDIRECT_VIEW);
				} catch (Exception ex) {

				}
			}
		}
	}
}
